import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        console.log('登录响应:', response)
        
        // 根据实际后端响应格式获取token
        let token = null
        if (response.data && response.data.code === 1) {
          if (response.data.data && typeof response.data.data === 'string') {
            // 如果data直接是token字符串
            token = response.data.data
          } else if (response.data.data && response.data.data.token) {
            // 如果data是对象，包含token字段
            token = response.data.data.token
          } else if (response.data.token) {
            // 如果token直接在data下
            token = response.data.token
          }
        }
        
        if (token) {
          console.log('成功获取token:', token)
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        } else {
          console.error('登录响应中未找到token:', response.data)
          reject('登录失败')
        }
      }).catch(error => {
        console.error('登录请求失败:', error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      console.log('开始获取用户信息，当前token:', getToken())
      
      getInfo().then(response => {
        console.log('获取用户信息响应:', response)

        if (!response.data) {
          console.error('验证失败: 响应中没有data字段')
          return reject('验证失败请重新登录.')
        }

        // 根据实际后端响应格式获取用户信息
        let userData = null
        if (response.data.code === 1 && response.data.data) {
          userData = response.data.data
        } else if (response.data.code === 0 && response.data.msg === 'NOT_LOGIN') {
          console.error('用户未登录或token已过期')
          return reject('登录已过期，请重新登录')
        } else {
          userData = response.data
        }

        console.log('解析的用户数据:', userData)

        // 获取用户信息
        let username = userData.username || userData.name || '未知用户'
        let avatar = userData.avatar || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        let roles = userData.roles || []

        console.log('原始角色列表:', roles)
        
        // 处理角色格式，确保是数组，并且包含正确的前缀
        if (typeof roles === 'string') {
          // 如果角色是字符串，转换为数组
          roles = [roles]
        }
        
        // 确保角色名称包含正确的前缀 'role_'
        roles = roles.map(role => {
          if (role === 'admin' || role === 'user') {
            return 'role_' + role
          }
          return role
        })
        
        console.log('处理后的角色列表:', roles)
        
        // 如果后端没有返回角色信息，添加默认角色
        if (!roles || roles.length === 0) {
          console.warn('后端未返回角色信息，使用默认角色')
          // 根据用户名设置不同角色
          if (username.toLowerCase().includes('admin')) {
            roles = ['role_admin']
            console.log('根据用户名判断为管理员角色')
          } else {
            roles = ['role_user']
            console.log('设置为默认普通用户角色')
          }
        }
        
        console.log('用户名:', username)
        console.log('头像:', avatar)
        console.log('最终角色列表:', roles)
        
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          console.error('角色列表为空，拒绝登录')
          return reject('用户角色必须是非空数组!')
        }
        
        commit('SET_ROLES', roles)
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        resolve(userData)
      }).catch(error => {
        console.error('获取用户信息失败:', error)
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

